
use mongodb::{bson::{doc, Document}, options::{ClientOptions, ServerApi, ServerApiVersion}, sync::{Client, Collection, Database}};


use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug)]
pub struct Kline {
    pub symbol: String,
    pub openTime: f64,
    pub openPrice: String,
    pub highPrice: String,
    pub lowPrice: String,
    pub closePrice: String,
    pub volume: String,
    pub closeTime:f64,
    pub quteAssetVolume: String,
    pub numberOftrades:i64,
    pub takerBuyBaseAssetVolume:String,
    pub takerBuyQuoteAssetVolume:String,
    pub unUsedField: String,
}

pub struct DB {
    client: Client,
    database: Database,
    h12 : Collection<Kline>,
}



impl DB {

    pub fn find_by_filter(&self, doc: Document,) -> Option<Vec<Kline>> {
        let mut cursor  = self.h12.find(doc).run().unwrap();
        let mut result : Vec<Kline> = Vec::new();
        for kline in cursor {
            result.push(kline.unwrap());
        }
        Some(result)
    }

}

pub fn init_db(mongod_url:String, data_name:String) -> Result<DB, Box<dyn std::error::Error>> {
    let mut client_options = ClientOptions::parse(mongod_url).run().unwrap();
    // Set the server_api field of the client_options object to Stable API version 1
   // let server_api = ServerApi::builder().version(ServerApiVersion::V1).build();
    //client_options.server_api = Some(server_api);
    // Create a new client and connect to the server
    let client = Client::with_options(client_options)?;
    let database = client.database(data_name.as_str());
    let h12_col = database.collection("h12klines");

    Ok(DB {
        client, database, h12: h12_col
    })
}